# 作者: 许可 <paokuai19@163.com>
# 许可证: Apache-2.0
# 说明: 一键构建并通过 OpenOCD 烧录到 STM32F103
$ErrorActionPreference = 'Stop'

# 切到脚本所在目录
Set-Location -LiteralPath $PSScriptRoot

# 基础检查（尽量避免复杂语法）
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { throw '未找到 cargo' }
if (-not (Get-Command rustup -ErrorAction SilentlyContinue)) { throw '未找到 rustup' }
if (-not (Get-Command openocd -ErrorAction SilentlyContinue)) { throw '未找到 openocd' }

# 确保目标已安装
$installedTargets = (rustup target list --installed | Out-String)
if ($installedTargets -notmatch 'thumbv7m-none-eabi') {
    rustup target add thumbv7m-none-eabi | Out-Host
}

# 构建 release
cargo build --release --target thumbv7m-none-eabi | Out-Host

$elf = Join-Path -Path $PSScriptRoot -ChildPath 'target/thumbv7m-none-eabi/release/stm32_test'
# 将路径转换为正斜杠，避免 TCL 将反斜杠当转义
$elfForOpenOcd = ($elf -replace '\\','/')
if (-not (Test-Path -LiteralPath $elf)) {
    throw ('未找到 ELF 产物: ' + $elf)
}

# 通过 OpenOCD 烧录（使用花括号包裹路径，避免 TCL 解释反斜杠）
& openocd -f openocd.cfg -c init -c 'reset halt' -c ("program {${elfForOpenOcd}} verify") -c 'reset run' -c exit
exit $LASTEXITCODE
